﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using SAKS.IServices;
using System.Drawing;
using SAKS.Models;
using NHibernate.Linq;
using SAKS.Services.Query;

namespace SAKS.Services
{
    public class PictureServices : IPictureServices
    {
        public NHibernate.ISession Session { get; set; }

        bool ThumbnailCallback()
        {
            return false;
        }

        public Guid SavePictureFile(byte[] pic)
        {
            MemoryStream ms = new MemoryStream(pic);        
            var picture = Image.FromStream(ms);
            var thumb = picture.GetThumbnailImage(100, 100, new Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
            MemoryStream thumbMs = new MemoryStream();
            thumb.Save(thumbMs, System.Drawing.Imaging.ImageFormat.Jpeg);
            var picFile = new PicFile
            {
                Original = pic,
                Thumbnail = thumbMs.GetBuffer()
            };
            var pictureId = (Guid)Session.Save(picFile);
            Session.Flush();
            return pictureId;
        }
        public Guid SavePictureInfo(PictureInfo info)
        {
            return (Guid)Session.Save(info);          
        }
        public Image GetThumbnail(Guid pictureId) 
        {
            var query = from p in Session.Query<PicFile>()
                        where p.Id == pictureId
                        select p.Thumbnail;
            MemoryStream ms = new MemoryStream(query.SingleOrDefault());
            var img = Image.FromStream(ms);
            return img;
        }
        public Image GetOriginal(Guid pictureId)
        {
            var query = from p in Session.Query<PicFile>()
                        where p.Id == pictureId
                        select p.Original;
            MemoryStream ms = new MemoryStream(query.SingleOrDefault());
            var img = Image.FromStream(ms);
            return img;
        }
        public PictureInfo GetInfo(Guid infoId)
        {
            return Session.Get<PictureInfo>(infoId);                       
        }
        public IEnumerable<PictureInfo> GetInfoList(Guid projectId, int start, int pageSize, out int? totalRecords)
        {
            PagedPictureInfoSearch infoSearch = new PagedPictureInfoSearch(Session) {
                First = start,
                PageSize = pageSize,
                ProjectId = projectId
            };
            var result = infoSearch.Execute();
            totalRecords = result.TotalItems;
            return result.PageOfResults;

        }
    }
}
